package com.shichenjia.fileupload.service.imp;


import com.shichenjia.fileupload.config.FileUploadConfig;
import com.shichenjia.fileupload.entrity.FileUpload;
import com.shichenjia.fileupload.mapper.FileUploadMapper;
import com.shichenjia.fileupload.service.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Calendar;
import java.util.UUID;

import org.springframework.util.StringUtils;

@Slf4j
@Service
public class FileUploadServiceImp implements FileUploadService {
    @Autowired
    private FileUploadMapper fileUploadMapper;
    @Autowired
    private FileUploadConfig fileUploadConfig;

    @Override
    public FileUpload uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        String filePath = year + "/" + month + "/" + day + "/";
        FileUpload fileUploadModel = new FileUpload();
        String fileExtension = StringUtils.getFilenameExtension(fileName);
        String id = UUID.randomUUID().toString();
        String basePath = fileUploadConfig.getSaveFilePath();
        fileUploadModel.setFileName(fileName);
        fileUploadModel.setFileType(file.getContentType());
        fileUploadModel.setFileSize(file.getSize());
        fileUploadModel.setFilePath(filePath);
        fileUploadModel.setFileExtension(fileExtension);
        fileUploadModel.setId(id);
        fileUploadModel.setFileUrl(basePath + id);
        String filePathNew = basePath + filePath;
        File createPath = new File(filePathNew);
        //如果不存在目录就创建目录
        if (!createPath.exists()) {
            createPath.mkdirs();
        }
        try {
            fileUploadMapper.insert(fileUploadModel);
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePathNew + id);
            Path savePath = Files.write(path, bytes);
            file.transferTo(savePath);
            log.info(path.toString());
            return fileUploadModel;
        } catch (Exception e) {
            log.error(e.getMessage());
            return null;
        }


    }

    @Override
    public ResponseEntity<Resource> getFile(String fileId) {
        try {
            FileUpload fileUpload = fileUploadMapper.selectById(fileId);
            if (ObjectUtils.isEmpty(fileUpload)) {
                return ResponseEntity.internalServerError().build();
            }
            Path path = Paths.get(fileUploadConfig.getSaveFilePath() + fileUpload.getFilePath() + fileId);
            log.info(path.toString());
            Resource resource = new UrlResource(path.toUri());
            if (resource.exists()) {
                return ResponseEntity
                        .ok()
                        .contentLength(fileUpload.getFileSize())
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .header("Content-Disposition", "attachment;filename=\\" + fileId + "\\")
                        .body(resource);
            }
        } catch (MalformedURLException e) {
            log.error(e.getMessage());
            return ResponseEntity.internalServerError().build();
        }
        return ResponseEntity.internalServerError().build();
    }
}
